var _controller = CTX + '/schedule/task';
var _findPage = _controller + '/findPage';
var _add = _controller + '/add';
var _update = _controller + '/update';
var _deletes = _controller + '/delete';
var _stop = _controller + '/stop';
var _start = _controller + '/start';
var _restart = _controller + '/restart';
var Req = {
    list: {method: 'GET', url: _controller},
    add: {method: 'POST', url: _controller},
    update: {method: 'PUT', url: _controller},
    del: {method: 'DELETE', url: _controller},
    export: {method: 'POST', url:_controller + '/export'},
    start: {method: 'POST', url:_controller + '/start'},
    stop: {method: 'POST', url:_controller + '/stop'},
    restart: {method: 'POST', url:_controller + '/restart'}
};


var inUseList = [{text: '启用', value: 1}, {text: '停用', value: 0}];
var inUseMap = {};

var $grid = null;
var $dlg = null;

$(function () {
    $grid = $('#scheduleGrid');
    $dlg = $('#dlg');

    inUseMap = changeListData2Map(inUseList, 'value');

    $('#sf_initStartFlag').combobox({
        data: inUseList,
        loadFilter: e_combobox_addall_filter
    });

    $('#fm_initStartFlag').combobox({
        data: inUseList,
        value: 1
    });

    initTaskGrid();

    $('#searchBtn').click(function () {
        var params = getQueryParams();
        $grid.datagrid('load', params);
    });

    $('#resetBtn').click(function () {
        $('#searchForm').form('reset');
        $('#searchBtn').trigger('click');
    });
})
;

function getQueryParams() {
    var params = $('#searchForm').serializeForm();
    return params;
}

function initTaskGrid() {
    $grid.datagrid({
        fit: true,
        // fitColumns: true,
        singleSelect: false,
        method: Req.list.method,
        url: Req.list.url,
        queryParams: getQueryParams(),
        // multiSort: true,
        sortName: 'id',
        sortOrder: 'asc',
        columns: [[{
            field: '_ckx_',
            checkbox: true
        }, {
            field: 'id',
            title: '任务ID',
            width: 80,
            sortable: true
        }, {
            field: 'taskKey',
            title: '任务标识',
            width: 150,
            sortable: true,
            formatter: function (v, row, i) {
                return '<a href="javascript:;" class="row-btn" title="' + row.name + '" onclick="see(' + i + ')">' + v + '</a>';
            }
        }, {
            field: 'taskDesc',
            title: '任务描述',
            width: 200
        }, {
            field: 'taskCron',
            title: '任务表达式',
            width: 150
        }, {
            field: 'initStartFlag',
            title: '是否在用',
            width: 100,
            formatter: function (v, row, i) {
                var inUse = inUseMap[v];
                if (inUse && inUse.value == v) {
                    return inUse.text;
                }
                return v;
            }
        }, {
            field: 'createTime',
            title: '创建时间',
            width: 150
        }, {
            field: 'updateTime',
            title: '修改时间',
            width: 150
        }, {
            field: '_opts_',
            title: '操作',
            width: 230,
            align: 'center',
            formatter: function (v, row, i) {
                var ary = [];
                if (row.initStartFlag == 1) {
                    ary.push('<a href="javascript:;" class="row-btn" onclick="stop(\'' + row.taskKey + '\')"><i class=" "></i> 停用</a>');
                    ary.push('<a href="javascript:;" class="row-btn" onclick="restart(\'' + row.taskKey + '\')"><i class=" "></i> 重新启用</a>');
                } else if (row.initStartFlag == 0) {
                    ary.push('<a href="javascript:;" class="row-btn" onclick="start(\'' + row.taskKey + '\')"><i class=" "></i> 启用</a>');
                }
                ary.push('<a href="javascript:;" class="row-btn" title="修改" onclick="update(' + i + ')"><i class=" fa fa-edit"></i></a>');
                ary.push('<a href="javascript:;" class="row-btn" title="删除" onclick="deletes(' + i + ')"><i class="fa fa-trash"></i></a>');
                return ary.join('&nbsp;<span class="btn-separator"></span>&nbsp;');
            }
        }]]
    });
}

function stop(taskKey) {
    $grid.datagrid('unselectAll');
    $.ajax({
        type: Req.stop.method,
        url: Req.stop.url,
        data: {
            taskKey: taskKey
        },
        dataType: 'json',
        success: function (result) {
            $grid.datagrid('reload');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}
function restart(taskKey) {
    $grid.datagrid('unselectAll');
    $.ajax({
        type: Req.restart.method,
        url: Req.restart.url,
        data: {
            taskKey: taskKey
        },
        dataType: 'json',
        success: function (result) {
            $grid.datagrid('reload');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}
function start(taskKey) {
    $grid.datagrid('unselectAll');
    $.ajax({
        type: Req.start.method,
        url: Req.start.url,
        data: {
            taskKey: taskKey
        },
        dataType: 'json',
        success: function (result) {
            $grid.datagrid('reload');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}

function add() {
    var $form = $dlg.find('form');
    $form.form('reset');

    $dlg.dialog({
        title: '新增定时任务',
        modal: true,
        inline: true,
        buttons: [{
            text: '确定',
            iconCls: 'e-icon fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(Req.add, formObj, function (roleId) {
                    $grid.datagrid('reload', {
                        id: roleId
                    });
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function update(rowIndex) {
    var row = null;
    if (rowIndex || rowIndex === 0) {
        $grid.datagrid('unselectAll');
        row = $grid.datagrid("getRows")[rowIndex];
    } else {
        row = $grid.datagrid('getSelections')[0];
    }
    if (!row) {
        $.showMsg('请选择一行数据！');
        return;
    }

    var $form = $dlg.find('form');
    $form.form('load', row);
    $dlg.dialog({
        title: '修改定时任务',
        modal: true,
        buttons: [{
            text: '确定',
            iconCls: 'fa fa-save',
            plain: true,
            handler: function () {
                var formObj = $form.serializeForm();
                $form.submitEForm(Req.update, formObj, function (roleId) {
                    $grid.datagrid('reload', {
                        id: roleId
                    });
                    $dlg.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function see(rowIndex) {
    $grid.datagrid('unselectAll');

    var role = $grid.datagrid("getRows")[rowIndex];

    $dlg.find('form').form('load', role);
    $dlg.dialog({
        title: '查看定时任务',
        modal: true,
        buttons: [{
            text: '关闭',
            iconCls: 'fa fa-close',
            plain: true,
            handler: function () {
                $dlg.dialog('close');
            }
        }]
    }).dialog('open');
}

function deletes(rowIndex) {
    if (rowIndex || rowIndex === 0) {
        $grid.datagrid('unselectAll');

        var row = $grid.datagrid("getRows")[rowIndex];
        $.confirmMsg('确定要删除定时任务[' + row.name + ']吗？', function () {
            doDelete([row.id]);
        });
    } else {
        var rows = $grid.datagrid('getSelections'), ids = [];
        if (rows && rows.length) {
            $.each(rows, function (i, row) {
                ids.push(row.id);
            });
            $.confirmMsg('确定要删除选择的[' + ids.length + ']条记录？', function () {
                doDelete(ids);
            });
        } else {
            $.showMsg('请选择要删除的记录');
        }
    }
}

function doDelete(ids) {
    $.ajax({
        type: Req.del.method,
        url: Req.del.url,
        data: {
            ids: ids.join(',')
        },
        dataType: 'json',
        success: function (result) {
            $grid.datagrid('reload');
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.dealResultData(XMLHttpRequest.responseJSON);
        }
    });
}